// 引入接口文件
import {regionArea,locationServ,verifyCodeFun,getTeamsByProjectId,getTeamUser,importExcel,deleteImportCustomer} from './talkMapServ.js'

// 对象和JSON字符串互转
import { parse } from 'qs'
// 弹出消息框
import { message } from 'antd'
import axios from 'axios'
import config from 'config/config'
// 日期处理对象
import moment from 'moment'
/* isEmpty 对象是否为空
 * isArray 对象是否数组
 * cloneDeep 对象深拷贝
 */
import {isEmpty, isArray, cloneDeep, merge} from 'lodash'

const queryList = [
  {
    name: '区域', type: 'selectClear', key: 'areaId', value: '', notNeedAll: true, list: []
  },
  {
    name: '项目', type: 'selectsSarch', key: 'projectId', value: '', notNeedAll: true, list:[]
  },
  {
    name: '渠道', type: 'selectClear', key: 'mapTchannelype', value: '行销自拓', notNeedAll: true, list: [
      {id: '行销自拓', name: '行销自拓'}
    ]
  },
  {
    name: '地图分类', type: 'selectClear', key: 'mapType', value: '0', notNeedAll: true, list: [
      {id: '0', name: '打点图'},
      {id: '1', name: '热力图'}
    ]
  },
  {
    name: '团队', type: 'selectClear', key: 'teamId', value: '', notNeedAll: true, list: []
  },
  {
    name: '团队成员', type: 'selectClear', key: 'userId', value: '', notNeedAll: true, list: []
  },
  {
    name: '客户状态', type: 'selectClear', key: 'customerType', value: '', notNeedAll: true, list: [
      {id: '全部', name: '全部'},
      {id: '未到访', name: '未到访'},
      {id: '已到访', name: '已到访'},
      {id: '已成交', name: '已成交'},
      {id: '导入客户', name: '导入客户'}
    ]
  },
  {
    name: '统计时间', type: 'date', key:'times', value: '', 
  },
]

// config props 热力图配置
const visible = true; 
const radius = 30; 
const gradient = {
  0.5: 'blue',
  0.65: 'rgb(117,211,248)',
  0.7: 'rgb(0, 255, 0)',
  0.9: '#ffea00',
  1.0: 'red'
};
const zooms = [3, 18]; 

const pluginProps = {
  visible,
  radius,
  gradient,
  zooms,
  dataSet:{
    data:[],
    max:100
  }
}

// 初始默认状态
const defultState = {
  loading: false,
  biz: {
		queryForm: {}
  },
  teamModal:{
    visible:false
  },
  selectedRowKeys: [],
  selectedRows: [],
  queryList,
  areaId:'',
  projectId:'',
  products:[],
  areaList:[],
  teamList: [],
  userList: [],
  markersGroup:[],
  mapType:'0',
  pluginProps//热力图配置
}



// 声明module
const tmpModule = {
  namespace: 'messageListModel',
  state: cloneDeep(defultState),
  subscriptions: {
    setup ({dispatch, history}) {
      history.listen(({ pathname, query }) => {
        if('' + tmpModule.pathname === '' + pathname){
          dispatch({ type: 'regionArea', payload:{}});
          dispatch({ type: 'updateStore', payload: cloneDeep(defultState) });
        }
      })
    },
  },
  // 方法列表
  effects: {
     //获取区域项目
    *regionArea({payload},{put,select,call}){
      let {areaList,queryList} = yield select(state => state[tmpModule.namespace])
      let params = {
          level : 2 
        }
      if(yield call(verifyCodeFun,{})){
       const { data } = yield call(regionArea, {...params})
        let list = data
        if(!list.length){
          return
        }
        areaList =  list.map((item,index)=>{
          return {
            name: item.buname,
            id: item.buguid,
            children: item.childSysUninessunitList
          }
        })
        queryList[0].list = areaList
        yield put({type: 'updateStore', payload: {areaList,queryList}})
      }
    },

  *getTeamsByProjectId({payload},{put,select,call}){
      let {teamList,queryList} = yield select(state => state[tmpModule.namespace])
      let params = {
        projectId:payload.projectId,
      }
      const { success,rows } = yield call(getTeamsByProjectId, {...params})
      if(success){
        teamList = rows
        if(!rows.length){
          return
        }
        teamList =  rows.map((item,index)=>{
          return {
            name: item.team_name,
            id: item.id,
          }
        })
        queryList[4].list = teamList
        yield put({type: 'updateStore', payload: {teamList,queryList}})
      }
  },
  *getTeamUser({payload},{put,select,call}){
    let {userList,queryList} = yield select(state => state[tmpModule.namespace])
    let params = {
        teamId : payload.teamId
      }
      const { success,rows } = yield call(getTeamUser, {...params})
      if(success){
        let newarr =  rows.filter(item => item.zituoRole == '3')
        if(!newarr.length) return
        userList =  newarr.map((item,index)=>{
          return {
            name: item.userName,
            id: item.userId,
          }
        })
        queryList[5].list = userList
        yield put({type: 'updateStore', payload: {userList,queryList}})
      }
  },

  // 删除表格数据
  * onDelete ({payload}, {put, call, select}) {
    let params = {
      fileName :payload.ids
    }
    let {data, success} = yield call(deleteImportCustomer, params)
    let {biz} = yield select(state => state[tmpModule.namespace])
    if(success){
      message.success('删除成功')
      biz.refreshListDatas(true)
    }
  },
  *exportTemplate({payload},{put,select,call}){
    axios({
        method: 'post',
        url: config.baseUrl+`zituo-admin/a/map/exportExcel`,
        responseType: 'blob',
        headers: {},
        data: {},
    }).then(res => {
        const content = res.data
        const blob = new Blob([content])
        Date.prototype.Format = function (fmt) { // author: meizz
            var o = {
                "M+": this.getMonth() + 1, // 月份
                "d+": this.getDate(), // 日
                "h+": this.getHours(), // 小时
                "m+": this.getMinutes(), // 分
                "s+": this.getSeconds(), // 秒
                "q+": Math.floor((this.getMonth() + 3) / 3), // 季度
                "S": this.getMilliseconds() // 毫秒
            };
            if (/(y+)/.test(fmt))
                fmt = fmt.replace(RegExp.$1, (this.getFullYear() + "").substr(4 - RegExp.$1.length));
            for (var k in o)
                if (new RegExp("(" + k + ")").test(fmt)) fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length)));
                    return fmt;
        }
        let dateTime = new Date().Format("yyyy-MM-dd hh:mm:ss");
        let fileName = `拓客地图导入模板 ${dateTime}.xls`
        if ('download' in document.createElement('a')) { // 非IE下载
          const elink = document.createElement('a')
          elink.download = fileName
          elink.style.display = 'none'
          elink.href = URL.createObjectURL(blob)
          document.body.appendChild(elink)
          elink.click()
          URL.revokeObjectURL(elink.href) // 释放URL 对象
          document.body.removeChild(elink)
        } else { // IE10+下载
          navigator.msSaveBlob(blob, fileName)
        }
        message.success('导出成功')
    })
  },
  *exportList({payload},{put,select,call}){
    let {projectId,queryList} = yield select(state => state[tmpModule.namespace])
    let params = {};
    params['areaId'] = queryList[0].value?queryList[0].value:''
    params['projectId'] = projectId?projectId:''
    params['type'] = queryList[3].value?queryList[3].value:''
    params['teamList'] = queryList[4].value?[queryList[4].value]:[]
    params['userList'] = queryList[5].value?[queryList[5].value]:[]
    params['startTime'] = queryList[7].value[0]?queryList[7].value[0]:''
    params['endTime'] = queryList[7].value[1]?queryList[7].value[1]:''
    if(params.teamList.length){
      if(!params.userList.length){
        message.warn('有选团队时，必须选择团队成员才能导出数据')
        return
      }
    }
    axios({
        method: 'post',
        url: config.baseUrl+`zituo-admin/a/map/exportAllCustomer`,
        responseType: 'blob',
        headers: {},
        data: params,
    }).then(res => {
        const content = res.data
        const blob = new Blob([content])
        Date.prototype.Format = function (fmt) { // author: meizz
            var o = {
                "M+": this.getMonth() + 1, // 月份
                "d+": this.getDate(), // 日
                "h+": this.getHours(), // 小时
                "m+": this.getMinutes(), // 分
                "s+": this.getSeconds(), // 秒
                "q+": Math.floor((this.getMonth() + 3) / 3), // 季度
                "S": this.getMilliseconds() // 毫秒
            };
            if (/(y+)/.test(fmt))
                fmt = fmt.replace(RegExp.$1, (this.getFullYear() + "").substr(4 - RegExp.$1.length));
            for (var k in o)
                if (new RegExp("(" + k + ")").test(fmt)) fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length)));
                    return fmt;
        }
        let dateTime = new Date().Format("yyyy-MM-dd hh:mm:ss");
        let fileName = `拓客地图数据报表 ${dateTime}.xls`
        if ('download' in document.createElement('a')) { // 非IE下载
          const elink = document.createElement('a')
          elink.download = fileName
          elink.style.display = 'none'
          elink.href = URL.createObjectURL(blob)
          document.body.appendChild(elink)
          elink.click()
          URL.revokeObjectURL(elink.href) // 释放URL 对象
          document.body.removeChild(elink)
        } else { // IE10+下载
          navigator.msSaveBlob(blob, fileName)
        }
        message.success('导出成功')
    })
  },
  *upload({payload},{put,select,call}){
      let {projectId} = yield select(state => state[tmpModule.namespace])
      let e = payload.e
      let file = e.target.files[0]
      let fileSize = (file.size) / 1024
      if (fileSize > 1024 * 20) {
          message.warn('文件大小不得超过 20M')
        return
      }
      let fileNameType = file.name.split('.').pop();
      let fileType = ['xlsx','xls']
      if (fileType.indexOf(fileNameType) < 0) {
          message.warn('文件格式必须为 xlsx 、xls')
        return
      }
      let fileInfo = new FormData()
      if (file) {
        fileInfo.append('file', file)
      }
      // let projectId = '812061b0-453f-11e9-a203-f9d6c38c6559'
      let params = {
        fileInfo:fileInfo,
        projectId:projectId,
        userId: localStorage.getItem('username')
      }

      let { success,value,hotValue} = yield call(importExcel, params)
      if(success){
        message.success('导入成功')
        yield put({type: 'search', payload: {}}) 
      }
  },
    
  //查询操作
  *search({ payload = {} }, { call, put, select }) {
    let {projectId,queryList,markersGroup,pluginProps} = yield select(state => state[tmpModule.namespace])
    //组装接口入参
    markersGroup = []
    let params = {
    };
    params['areaId'] = queryList[0].value?queryList[0].value:''
    params['projectId'] = projectId?projectId:''
    params['type'] = queryList[3].value?queryList[3].value:''
    params['teamList'] = queryList[4].value?[queryList[4].value]:[]
    params['userList'] = queryList[5].value?[queryList[5].value]:[]
    params['startTime'] = queryList[7].value[0]?queryList[7].value[0]:''
    params['endTime'] = queryList[7].value[1]?queryList[7].value[1]:''
    yield put({type: 'updateStore', payload: {loading: true}})
    const { success,value,hotValue,message} = yield call(locationServ, {...params})
    if(message){
      yield put({type: 'updateStore', payload: {loading: false}}) 
    }
    if(success){
      if(queryList[6].value=='全部'|| !queryList[6].value){
        if(queryList[4].value || queryList[5].value){
          pluginProps.dataSet.data = hotValue&&hotValue.length?hotValue.filter(item => item.type != '4'):[]
        }else{
          markersGroup = value&&value.importCustomer?[...value.importCustomer]:[]
          pluginProps.dataSet.data = hotValue&&hotValue.length?hotValue:[]
        }
        markersGroup = value&&value.sign?[...markersGroup,...value.sign]:[...markersGroup]
        markersGroup = value&&value.report?[...markersGroup,...value.report]:[...markersGroup]
        markersGroup = value&&value.visit?[...markersGroup,...value.visit]:[...markersGroup]
      }else if(queryList[6].value=='未到访'){
        markersGroup = value&&value.report?value.report:[]
        pluginProps.dataSet.data = hotValue&&hotValue.length?hotValue.filter(item => item.type == '0'):[]
      }else if(queryList[6].value=='已到访'){
        markersGroup = value&&value.visit?value.visit:[]
        pluginProps.dataSet.data = hotValue&&hotValue.length?hotValue.filter(item => item.type == '1'):[]
      }else if(queryList[6].value=='已成交'){
        markersGroup = value&&value.sign?value.sign:[]
        pluginProps.dataSet.data = hotValue&&hotValue.length?hotValue.filter(item => item.type == '2'):[]
      }else if(queryList[6].value=='导入客户'){
        markersGroup = value&&value.importCustomer?value.importCustomer:[]
        pluginProps.dataSet.data = hotValue&&hotValue.length?hotValue.filter(item => item.type == '4'):[]
      }
      
      yield put({type: 'updateStore', payload: {loading: false,markersGroup,pluginProps}}) 
    }
  },
  // 查询条件重置
  *queryReset({ }, { call, put, select }) {
    let { areaList,markersGroup,pluginProps} = yield select(state => state[tmpModule.namespace])
    let newQueryList = cloneDeep(queryList)
    newQueryList[0].list = areaList
    markersGroup = []
    pluginProps.dataSet.data = []
    yield put({ type: 'updateStore', payload: { queryList:newQueryList ,markersGroup,pluginProps} });
  },

   //改变查询条件
   *inputChange({ payload }, { call, put, select }) {
    let { areaId,projectId,queryList,markersGroup} = yield select(state => state[tmpModule.namespace])
    const { key, value } = payload;
    let data = queryList.find(item => item.key === key);

    if(data.key == 'areaId'){
      yield put({type: 'filterProjectList', payload:{areaId:value}})
      areaId = value
      yield put({ type: 'updateStore', payload: { areaId } });

    }else if(data.key == 'projectId'){
      if(queryList[1].list.length){
        let id = ''
        for(var item of queryList[1].list){
          if(item.name == value){
            id = item.id
          }
        }
        yield put({type: 'getTeamsByProjectId', payload:{projectId:id}})
        projectId = id
        yield put({ type: 'updateStore', payload: { projectId } });
      }

    }else if(data.key == 'mapType'){
      markersGroup=[]
      yield put({ type: 'updateStore', payload: { mapType:value,markersGroup,pluginProp:pluginProps } });

    }else if(data.key == 'teamId'){

      yield put({type: 'getTeamUser', payload:{teamId:value}})
    }else if(data.key == 'customerType'){

      yield put({ type: 'updateStore', payload: { queryList } });
    }else if(data.key == 'times'){
      queryList[7].value = value
      yield put({ type: 'updateStore', payload: { queryList } });
    }

    data.value = value;
    //刷新列表参数
    yield put({ type: 'updateStore', payload: { queryList: [...queryList, ...data] } });
  },

  *filterProjectList({payload},{put,select,call}){    
    let {products,areaList,queryList} = yield select(state => state[tmpModule.namespace])
    let list = []
    for(var item of areaList){
      if(payload.areaId&&item.id == payload.areaId){
        list = item.children
      }
    }
    if(list.length){
      products =  list.map((item,index)=>{
        return {
          name: item.buname,
          id: item.buguid,
        }
      })
    }
    queryList[1].list = products
    yield put({type: 'updateStore', payload: {products,queryList}})
  },
  * selectedKeysChange ({payload}, {put, select, call}) {
    let {selectedRowKeys,selectedRows} = yield select(state => state[tmpModule.namespace])
    
    selectedRowKeys=payload.selectedRowKeys
    selectedRows=payload.selectedRows
    yield put({
      type: 'updateStore',
      payload: {
        selectedRowKeys,selectedRows
      }
    })
  },
  },
  
  // 存入状态机
  reducers: {
    updateStore(preState, action) {
      return { ...preState, ...action.payload };
    }
  }
}

export default tmpModule
